#include "qdriverlistview.h"

#include "stylehelper.h"
#include "qbaseitemdelegate.h"

#include "../shared/qdriverfactory.h"

#include <QHeaderView>
#include <QPainter>
#include <QMouseEvent>

QDriverListView::QDriverListView(QWidget *parent) :
    QTreeWidget(parent),
    m_select_item(NULL)
{

    QString group;
    QString name;
    QIcon icon=StyleHelper::drawIndicatorIcon(this->palette(),this->style());
    foreach(tagDriverInfo* info,QDriverFactory::get_driver_info())
    {
        group=info->m_show_group;
        name=info->m_show_name;
        QTreeWidgetItem *par=m_group_to_item.value(group);
        if(par==NULL)
        {
            par=new QTreeWidgetItem(this);
            par->setText(0,group);
            par->setIcon(0,icon);
            par->setExpanded(true);
            m_group_to_item.insert(group,par);
            for(int i=0;i<columnCount();i++)
            {
                par->setData(i,DarkRole,true);
            }
        }

        QTreeWidgetItem *item=new QTreeWidgetItem(par);
        item->setText(0,name);
        m_item_to_type.insert(item,info->m_name);
        if(m_select_item==NULL)
        {
            m_select_item=item;
            m_select_item->setIcon(0,QIcon(":/images/check.png"));
        }
    }

    this->setAlternatingRowColors(true);
    this->setRootIsDecorated(false);
    this->header()->hide();
    this->setItemDelegate(new QBaseItemDelegate);
    this->setMinimumSize(100,200);
    connect(this,SIGNAL(itemClicked(QTreeWidgetItem*,int)),this,SLOT(item_click(QTreeWidgetItem*)));
}

void QDriverListView::item_click(QTreeWidgetItem *item)
{
    if(m_item_to_type.keys().contains(item))
    {
        if(m_select_item!=NULL)
        {
            m_select_item->setIcon(0,QIcon());
        }
        m_select_item=item;
        m_select_item->setIcon(0,QIcon(":/images/check.png"));
    }
}

QString QDriverListView::get_type()
{
    return m_item_to_type.value(m_select_item);
}

void QDriverListView::drawRow(QPainter *painter, const QStyleOptionViewItem &options, const QModelIndex &index) const
{
    QColor c;
    QStyleOptionViewItem opt=options;
    if(index.data(DarkRole).toBool())
    {
        c=opt.palette.color(QPalette::Dark);
    }
    else
    {
        c=QColor(BACKGROUND_COLOR);
    }
    painter->fillRect(options.rect,c);
    opt.palette.setColor(QPalette::AlternateBase,c.lighter(112));
    QTreeWidget::drawRow(painter,opt,index);
}

void QDriverListView::mousePressEvent(QMouseEvent *event)
{
    if(event->pos().x()<20)
    {
        QTreeWidgetItem *item=itemAt(event->pos());
        if(item!=NULL)
        {
            item->setExpanded(!item->isExpanded());
        }
    }
    QTreeWidget::mousePressEvent(event);
}
